﻿using System;
using System.Collections.Generic;
using System.Linq;
using CoreShop.Model.OrderModels;
using System.Threading;
using gregn6Lib;
using System.Data;
using CoreShop.Services;
using CoreShop.Model;
using Sunny.UI;

namespace CoreShop.PrintService
{
    public class MallOrderPrintServices
    {
        //定义Grid++Report报表主对象
        GridppReport Report = null;

        /// <summary>
        /// 在线订单模板
        /// </summary>
        /// <param name="itemList"></param>
        public OnlineOrderModel OnlineOrderPrintModel { get; set; }

        //传入参数
        public void OnlineOrderReportFetchRecord()
        {
            OnlineOrderReportFetchRecord(Report, OnlineOrderPrintModel);
        }

        /// <summary>
        /// 明细网格数据源
        /// </summary>
        /// <param name="Report"></param>
        /// <param name="itemMaster"></param>
        public static void OnlineOrderReportFetchRecord(IGridppReport Report, OnlineOrderModel OnlineOrderInfo)
        {
            var XcxOrderItem = OnlineOrderInfo.XcxOrderItem;
            if (XcxOrderItem == null || XcxOrderItem.Count <= 0)
            {
                return;
            }
            //创建一个名为"tableName"的空表
            DataTable dt = new DataTable("tableName");
            //创建传入对象名称的列
            foreach (var items in XcxOrderItem.FirstOrDefault().GetType().GetProperties())
            {
                dt.Columns.Add(items.Name);
            }
            dt.Columns.Add("salseAmt");
            XcxOrderItem.ForEach(d =>
            {
                var dr = dt.NewRow();
                dr["LineNo"] = d.lineNo;
                dr["spuCode"] = d.spuCode;
                dr["spuName"] = d.itemName;
                dr["num"] = d.num;
                dr["price"] = d.price;
                dr["sourcePrice"] = d.SourcePrice;
                dr["salseAmt"] = d.price * (!string.IsNullOrEmpty(d.num) ? Convert.ToDecimal(d.num) : 0);
                dr["ShareAmount"] = d.ShareAmount;
                dt.Rows.Add(dr);
            });
            GridppReportUtilityHelp.FillRecordToReportData(Report, dt);
        }

        //传入参数
        private void OnlineOrderReportInitialize()
        {
            try
            {
                if (OnlineOrderPrintModel == null)
                {
                    return;
                }
                if (Report.ParameterByName("店铺名称") != null)
                {
                    Report.ParameterByName("店铺名称").AsString = string.IsNullOrEmpty(OnlineOrderPrintModel.BaseBranchInfo.BranchName) ? "" : OnlineOrderPrintModel.BaseBranchInfo.BranchName;
                }
                if (Report.ParameterByName("在线订单") != null)
                {
                    Report.ParameterByName("在线订单").AsString = string.IsNullOrEmpty(OnlineOrderPrintModel.orderSn) ? "" : OnlineOrderPrintModel.orderSn;
                }
                if (Report.ParameterByName("用户名称") != null)
                {
                    Report.ParameterByName("用户名称").AsString = string.IsNullOrEmpty(OnlineOrderPrintModel.userName) ? "" : OnlineOrderPrintModel.userName;
                }
                if (Report.ParameterByName("用户电话") != null)
                {
                    Report.ParameterByName("用户电话").AsString = string.IsNullOrEmpty(OnlineOrderPrintModel.userPhone) ? "" : OnlineOrderPrintModel.userPhone;
                }
                if (Report.ParameterByName("销售数量") != null)
                {
                    Report.ParameterByName("销售数量").AsString = OnlineOrderPrintModel.ItemNumber + "";
                }
                if (Report.ParameterByName("支付方式") != null)
                {
                    string PayNmae = "";
                    if (OnlineOrderPrintModel.PayType == "0")
                    {
                        PayNmae = "微信支付";
                    }
                    else if (OnlineOrderPrintModel.PayType == "1")
                    {
                        PayNmae = "余额";
                    }
                    else
                    {
                        PayNmae = "未知";
                    }
                    Report.ParameterByName("支付方式").AsString = PayNmae;
                }
                if (Report.ParameterByName("订单金额") != null)
                {
                    Report.ParameterByName("订单金额").AsString = OnlineOrderPrintModel.totalAmount + "";
                }
                if (Report.ParameterByName("支付时间") != null)
                {
                    Report.ParameterByName("支付时间").AsString = string.IsNullOrEmpty(OnlineOrderPrintModel.payTime.ToString()) ? "" : OnlineOrderPrintModel.payTime.ToString();
                }
                if (Report.ParameterByName("备注") != null)
                {
                    Report.ParameterByName("备注").AsString = string.IsNullOrEmpty(OnlineOrderPrintModel.Remark) ? "" : OnlineOrderPrintModel.Remark;
                }
                if (Report.ParameterByName("配送用户名") != null)
                {
                    Report.ParameterByName("配送用户名").AsString = string.IsNullOrEmpty(OnlineOrderPrintModel.XcxOrderLine?.consigneeName) ? "" : OnlineOrderPrintModel.XcxOrderLine?.consigneeName;
                }
                if (Report.ParameterByName("配送收货电话") != null)
                {
                    Report.ParameterByName("配送收货电话").AsString = string.IsNullOrEmpty(OnlineOrderPrintModel.XcxOrderLine?.consigneePhone) ? "" : OnlineOrderPrintModel.XcxOrderLine?.consigneePhone;
                }
                if (Report.ParameterByName("配送收货地址") != null)
                {
                    Report.ParameterByName("配送收货地址").AsString = string.IsNullOrEmpty(OnlineOrderPrintModel.XcxOrderLine?.consigneeAddress) ? "" : OnlineOrderPrintModel.XcxOrderLine?.consigneeAddress;
                }
                if (Report.ParameterByName("订单类型") != null)
                {
                    string orderType = "小程序";
                    if (OnlineOrderPrintModel.DispatchingType == "1")
                    {
                        orderType = "自提";
                    }
                    else if (OnlineOrderPrintModel.DispatchingType == "2")
                    {
                        orderType = "配送";
                    }
                    Report.ParameterByName("订单类型").AsString = orderType;
                }

                if (Report.ParameterByName("订单状态") != null)
                {
                    Report.ParameterByName("订单状态").AsString = OnlineOrderPrintModel.StatusName;
                }
            }
            catch (Exception ex)
            {
                //Log.LogManage.Error("会员储值打印瑞浪报表参数传递错误：" + ex);
            }
        }

        public void SetPrintMallOrder(OnlineOrderModel OnlineOrderInfo, bool isPrintPreview = false)
        {
            if (OnlineOrderInfo == null) return;
            var schemedetailList = new corecmsprintschemedetailServices().SelectByBilltypeId((int)Library.GlobalEnumVars.PrintbillType.MallOrder);
            if ((schemedetailList == null) || (schemedetailList.Count == 0)) return;

            try
            {
                var ordermaster = new corecmsordermasterServices().GetById(OnlineOrderInfo.id);
                if ((ordermaster != null) && (ordermaster.checkFlag == true)) OnlineOrderInfo.Status = 5;
                
                OnlineOrderPrintModel = OnlineOrderInfo;
                foreach (var schemedetail in schemedetailList)
                {
                    if (schemedetail.billtemplate == null) continue;
                    if (string.IsNullOrEmpty(schemedetail.billtemplate.reportData)) return;
                    OnlineOrderPrint(schemedetail.billtemplate, isPrintPreview);
                }
            }
            catch (Exception ex)
            {
                //Log.LogManage.Error(string.Format("打印错误RL在线订单打印打印CommonPrintHandOver：{0}.", ex.Message));
                return;
            }
        }

        public void OnlineOrderPrint(corecmsprintbilltemplate billtemplate, bool isPrintPreview = false)
        {
            //定义Grid++Report报表主对象
            Report = new GridppReport();
            string PrintCellQty = "1";
            if (billtemplate.reportData.IsNullOrEmpty())
            {
                string sFile = System.Windows.Forms.Application.StartupPath + "\\report\\" + billtemplate.reportFile;
                Report.LoadFromFile(sFile);
            }
            else
            {
                Report.LoadFromStr(billtemplate.reportData);
            }
            //连接报表事件
            Report.FetchRecord += new _IGridppReportEvents_FetchRecordEventHandler(OnlineOrderReportFetchRecord);
            //连接报表取数事件
            Report.Initialize += new _IGridppReportEvents_InitializeEventHandler(OnlineOrderReportInitialize);
            if (Report.DetailGrid != null)
            {
                //设置页栏数
                Report.DetailGrid.PageColumnCount = string.IsNullOrEmpty(PrintCellQty) ? 1 : Convert.ToInt32(PrintCellQty);
            }
            if (!string.IsNullOrEmpty(billtemplate.printerName) && (billtemplate.printerName != "默认打印机"))
                Report.Printer.PrinterName = billtemplate.printerName;
            if (isPrintPreview)
            {
                Report.PrintPreview(true);
            }
            else
                Report.Print(false);
        }

    }
}
